package com.itjiange.reglg.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.itjiange.reglg.constant.CommonConstant;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA 对称加密
 *
 * @author ItJiange
 * @date 2023/11/13
 */
public class RSAUtils {

    /**
     * 利用私钥解密
     *
     * @param passStr 待解密字符串
     * @return
     */
    public static String decryptPass(byte[] passStr, String privateKeyCode) {
        RSA rsa = new RSA(privateKeyCode, null);
        // 解密为字符串
        byte[] decrypted = rsa.decrypt(passStr, KeyType.PrivateKey);
        return StrUtil.str(decrypted, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 利用私钥解密
     *
     * @param passStr 待解密字符串
     * @return
     */
    public static String decryptPass(String passStr, String privateKeyCode) {
        RSA rsa = new RSA(privateKeyCode, null);
        // 解密为字符串
        return rsa.decryptStr(passStr, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 随机生成公钥、私钥
     * @return map.get(0) 为私钥，map.get(1) 为公钥
     */
    public static Map<Integer, String> genKeyPair() {
        RSA rsa = new RSA();
        Map<Integer, String> map = new HashMap<>();

        String privateKey = rsa.getPrivateKeyBase64();
        String publicKey = rsa.getPublicKeyBase64();

        map.put(0, privateKey);
        map.put(1, publicKey);
        return map;
    }
}
